<?php


parse_str($_POST['serialized']);

$position = array();

for($i=0;$i<count($image);$i++) {
	if ($image[$i] == $_POST['sorted_id']) {
		if ($i == 0) {
			$position['id'] = $image[$i+1];
			$position['relative'] = 'before';
		} else {
			$position['id'] = $image[$i-1];
			$position['relative'] = 'after';
		}
		break;
	}
}

$folder_id = $db->fetchOne("SELECT folder_id FROM cms_images WHERE id=?", $_POST['sorted_id']);
$images    = $db->fetchPairs("SELECT id, sort FROM cms_images WHERE folder_id=?", $folder_id);

$images[$_POST['sorted_id']] = $images[$position['id']] + ($position['relative'] == 'after' ? +5 : -5);
asort($images);

$sort = 10;

$sorted_ids = array_keys($images);
foreach($sorted_ids as $id) {
	$db->update('cms_images', array('sort' => $sort), $db->quoteInto('id=?', $id));
	$sort+=10;
}
